package com.zw.april14thh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zw.april14thh.dao.BusinessDao;
import com.zw.april14thh.entity.AdminUser;
import com.zw.april14thh.entity.Business;
import com.zw.april14thh.entity.QueueNumber;
import com.zw.april14thh.service.AdminUserService;
import com.zw.april14thh.service.BusinessService;
import com.zw.april14thh.vo.AjaxResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class BusinessServiceImpl extends ServiceImpl<BusinessDao, Business> implements BusinessService {

    @Autowired
    QueueNumber queueNumber;

    @Autowired
    AdminUserService adminUserService;
    @Override
    public AjaxResult getAllQue() {

        LocalDate today = LocalDate.now();

        List<Object> objects = baseMapper.selectObjs(new QueryWrapper<Business>()
                .select("queue_id")
                .eq("status", 1)
                .apply("DATE(start_time) = DATE('" + today.toString() + "')"));

        List<String> strings = new ArrayList<>();
        objects.stream().forEach(o -> strings.add(o.toString()));

        List<Business> status = list(new QueryWrapper<Business>()
                .eq("status", 2)
                .apply("DATE(start_time) = DATE('" + today.toString() + "')"));

        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("queue",strings);
        stringObjectHashMap.put("needDo",status);
        return AjaxResult.success(stringObjectHashMap);
    }

    @Override
    public AjaxResult getAllByAdminUser(int pageNum,int pageSize,Integer adminId) {
        LocalDate today = LocalDate.now();
        AdminUser byId = adminUserService.getById(adminId);
        Integer types = byId.getTypes();
        if (byId == null ) {
            return AjaxResult.error("参数错误");
        }
        List<Integer> result = Arrays.stream(new int[]{1, 2, 4})
                .filter(x -> (types & x) == x)
                .boxed()
                .collect(Collectors.toList());

        Page<Business> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Business> wrapper = new QueryWrapper<Business>()
                .apply("DATE(start_time) = DATE('" + today.toString() + "')")
                .in("type", result)
                .ne("status", 0)
                .orderByDesc("start_time");
        List<Business> records = baseMapper.selectPage(page, wrapper).getRecords();
        return AjaxResult.success(records);
    }

    @Override
    public AjaxResult callMemberUser(String id,Integer adminId ) {

        Business byId = getById(id);
        if (byId == null){
            return AjaxResult.error("叫号失败，业务不存在");
        }
        if (byId.getStatus()!=1){
            return AjaxResult.error("该用户已被叫号");
        }
        byId.setStatus(2);
        byId.setAdminId(adminId);
        byId.setWindowId(adminUserService.getById(adminId).getWindowId());
        byId.setDoTime(new Date());
        updateById(byId);


        return AjaxResult.success();
    }

    @Override
    public AjaxResult getCountNoDo() {
        LocalDate today = LocalDate.now();
        List<Business> status = list(new QueryWrapper<Business>()
                .apply("DATE(start_time) = DATE('" + today.toString() + "')")
                .eq("status", 1)
        );

        HashMap<String, Integer> map = new HashMap<>();
        map.put("ztk",0);
        map.put("dljg",0);
        map.put("pbzj",0);
        for (Business business : status) {
            if (business.getType()==1){
                map.put("ztk",map.get("ztk")+1);
            }else if (business.getType()==2){
                map.put("dljg",map.get("dljg")+1);
            }else if (business.getType()==4){
                map.put("pbzj",map.get("pbzj")+1);
            }
        }

//
////        return AjaxResult.success();
//        LocalDate today = LocalDate.now();
//        List<Business> status = list(new QueryWrapper<Business>()
//                .apply("DATE(start_time) = DATE({0})", today)
//                .eq("status", 1)
//        );
//
//        Map<String, Integer> map = new HashMap<>();
//        for (Business business : status) {
//            Integer type = business.getType();
//            map.put("type:"+type, map.getOrDefault(type, 0) + 1);
//        }

        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult queuingUp(Integer type, Integer userId) {
        LocalDate today = LocalDate.now();
        Business one = getOne(new QueryWrapper<Business>().eq("user_id", userId)
                .eq("type", type)
                .in("status", 1, 2)
                .apply("DATE(start_time) = DATE('" + today.toString() + "')")
                .last("limit 1")
        );
        if (one != null) {
            return AjaxResult.success("无需填写");
        }
        return AjaxResult.success("需要填写");
    }

    @Override
    public AjaxResult information(Integer userId, Integer type, String unitName, String contacts, String contactNumber) {
        HashMap<String, String> map = new HashMap<>();

        try {

            //这里再确认一下  要不要再次判断是否需要填写

            AjaxResult ajaxResult = queuingUp(type, userId);
            if (ajaxResult.getMsg() .equals("无需填写")){
                map.put("NeedFill","no");
                return AjaxResult.success(map);
            }
            Business business = new Business();

            //先给相应队列进行排队
            queueNumber.update(type);
            business.setUserId(userId);
            business.setType(type);
            business.setQueueId(queueNumber.getQueueNumber(type));
            business.setUnitName(unitName);
            business.setContacts(contacts);
            business.setContactsPhone(contactNumber);
            business.setStartTime(new Date());
            business.setStatus(1);
            save(business);

        }catch (Exception e) {
            queueNumber.rollBack(type);
            return AjaxResult.error("填写信息时出现错误");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult queuingStatus(Integer userId) {
        LocalDate today = LocalDate.now();
        Business one = getOne(new QueryWrapper<Business>().eq("user_id", userId)
                .apply("DATE(start_time) = DATE({0})", today)
                .notIn("status", 0)
                .orderByDesc("start_time")
                .last("limit 0,1")
        );
        HashMap<String, Object> map = new HashMap<>();
        if (one ==null) {
            map.put("business",new Business(5));
            return AjaxResult.success(map);
        }
        if (one.getStatus() == 1) {
            Long type = baseMapper.selectCount(new QueryWrapper<Business>()
                    .eq("type", one.getType())
                    .apply("DATE(start_time) = DATE('" + today.toString() + "')")
                    .eq("status",1)
            );
            map.put("num",type+"");
            map.put("queueId",one.getQueueId());
        }else
        if (one.getStatus()==3){
             if (System.currentTimeMillis()-one.getOverTime().getTime()>1999){
                 map.put("business",new Business(5));
                 return AjaxResult.success(map);
             }
        }
        map.put("business",one);
        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult cancelQueuing(String userId) {
        LocalDate today = LocalDate.now();
        Business one = getOne(new QueryWrapper<Business>().eq("user_id", userId)
                .apply("DATE(start_time) = DATE({0})", today)
                .notIn("status", 0,3.4)
                .last("limit 1")
        );
        HashMap<String, Object> map = new HashMap<>();
        if (one == null){
            map.put("business",new Business(5));
            return AjaxResult.success(map);
        }
        one.setStatus(0);
        one.setCancelTime(new Date());
        updateById(one);
        map.put("business",one);
        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult doOverBusiness(String id) {

        Business byId = getById(id);
        if (byId == null){
            return AjaxResult.error("办结失败，业务不存在");
        }
        if (byId.getStatus() !=2){
            return AjaxResult.error("办结失败，未被叫号无法办结");
        }
        byId.setStatus(3);
        byId.setOverTime(new Date());

        updateById(byId);

        return AjaxResult.success();
    }

    @Override
    public AjaxResult cancelBussiness(String id) {
        Business byId = getById(id);
        if (byId == null){
            return AjaxResult.error("取消失败，业务不存在");
        }
        if (byId.getStatus() !=2){
            return AjaxResult.error("取消失败，未叫号无法取消");
        }
        byId.setStatus(4);
        updateById(byId);

        return AjaxResult.success();
    }
}
